package cn.enaium.message.specific;

import cn.enaium.message.config.JdbcConfig;
import cn.enaium.message.entity.Mdata;
import cn.enaium.message.entity.Muser;
import cn.enaium.message.repository.MdataRepository;
import cn.enaium.message.repository.MuserRepository;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;

//注册
public class Logon {
    public boolean RegisterUser(String name, String password, String email) {
        //获取SQLSession
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession = jdbcConfig.getSqlSession();
        //获取用户密码接口的代理对象
        MuserRepository muserRepository = sqlSession.getMapper(cn.enaium.message.repository.MuserRepository.class);
        int hasemail =  StringUtils.isNumeric(String.valueOf(muserRepository.findByEmailMuser(email))) ?muserRepository.findByEmailMuser(email) : 0;
        if (hasemail >=1) {
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return false;
        }
        Muser muser = new Muser();
        //添加用户密码
        muser.setName(name);
        String pas = DigestUtils.md5Hex(DigestUtils.md5Hex(password));
        muser.setPassword(pas);
        muser.setEmail(email);
        //添加Muser
        int result = muserRepository.saveMuser(muser);
        //判断是否添加成功
        if (result < 0) {
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return false;
        }
        sqlSession.commit();
        int museremail = muserRepository.findByEmailMuser(muser.getEmail());
        Mdata mdata = new Mdata();
        //获取用户资料接口的代理对象，同步添加用户个人信息
        MdataRepository mdataRepository = sqlSession.getMapper(cn.enaium.message.repository.MdataRepository.class);
        //添加用户资料
        mdata.setUid((long) museremail);
        mdata.setName(muser.getName());
        mdata.setSex("未知");
        mdata.setAutograph("暂无个性签名");
        int resultend = mdataRepository.saveMdata(mdata);
        //返回是否成功
        if (resultend < 0) {
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return false;
        } else {
            //关闭Sql链接
            sqlSession.commit();
            jdbcConfig.sqlSessionCommit();
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return resultend > 0;
        }
    }
}
